package com.baosight.risk.service.fltd.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baosight.risk.api.fltd.FltdOATaskService;
import com.baosight.risk.api.fltd.FltdTaskService;
import com.baosight.risk.api.xtaa.code.IXtaaCodeService;
import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskHistoryVO;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyUser;

@Service
public class FltdTaskServiceImpl implements FltdTaskService {

    @Autowired
    private FltdTaskMapper fltdTaskMapper;

    @Autowired
    private IXtzyCompanyService xtzyCompanyService;
    @Autowired
    private FltdOATaskService fltdOATaskService;
    @Autowired
    private IXtaaCodeService xtaaCodeService;

    @Override
    public int insert(FltdTask fltdTask) {
        return fltdTaskMapper.insert(fltdTask);
    }

    @Override
    public FltdTask selectTaskByTodoGuid(String todoGuid) {
        return fltdTaskMapper.selectByPrimaryKey(todoGuid);
    }

    @Override
    public List<FltdTask> selectTaskList(String queryType, FltdTaskVO param, String userCode) {
        List<FltdTask> fltdTasks = new ArrayList<>();
        if ("1".equals(queryType)) {
            fltdTasks = fltdTaskMapper.selectTodoTask(userCode);
        } else if ("2".equals(queryType)) {
            fltdTasks = fltdTaskMapper.selectFinishTask(userCode);
        } else if ("3".equals(queryType)) {
            fltdTasks = fltdTaskMapper.selectTaskList(param);
        }
        return fltdTasks;
    }

    @Override
    public List<FltdTask> selectGroupedTask(String userCode, String flowNo, String nodeCode) {
        List<FltdTask> fltdTasks = fltdTaskMapper.selectGroupedTask(userCode, flowNo, nodeCode);
        return fltdTasks;
    }

    @Override
    public FltdTask selectBeforeTask(String procGuid, String nodeCode) {
        return fltdTaskMapper.selectBeforeTask(procGuid, nodeCode);
    }

    @Override
    public List<FltdTask> selectCancelTask(String todoGuid, String procGuid, String userCode) {
        return fltdTaskMapper.selectCancelTask(todoGuid, procGuid, userCode);
    }

    @Override
    public List<FltdTaskHistoryVO> selectHistory(String procGuid) {
        return fltdTaskMapper.selectHistory(procGuid);
    }

    @Override
    public FltdTask selectExistTask(FltdTask fltdTask) {
        return fltdTaskMapper.selectExistTask(fltdTask);
    }

    @Override
    public String selectProcId(String flowNo, String taskGuid, String bizGuid) {
        flowNo="";
        return fltdTaskMapper.selectProcId(flowNo, taskGuid, bizGuid);
    }

    @Override
    public int selectTaskCount(String userCode) {
        return fltdTaskMapper.selectTaskCount(userCode);
    }

    @Override
    public int updateTaskStatus(FltdTask fltdTask) {
        return fltdTaskMapper.updateTaskStatus(fltdTask);
    }

    @Override
    public int updateByPrimaryKeySelective(FltdTask fltdTask) {
        return fltdTaskMapper.updateByPrimaryKeySelective(fltdTask);
    }

    @Override
    public List<FltdTask> selectOwnerTask(String userCode, String bizName, String bizDesc, String acctYear, String quarterCurrent) {
        if (StringUtils.isNotEmpty(acctYear)) {
            acctYear = acctYear.split("-")[0];
        }
        if ("admin".equals(userCode)) {
            userCode = null;
        }
        return fltdTaskMapper.selectOwnerTask(userCode, bizName, bizDesc, acctYear, quarterCurrent);
    }

    @Override
    public int selectMessageCount(String userCode) {
        return fltdTaskMapper.selectMessageCount(userCode);
    }

    @Override
    public List<FltdTask> selectMessageList(String queryType, FltdTaskVO param, String userCode) {
        List<FltdTask> fltdTasks = new ArrayList<>();
        if ("1".equals(queryType)) {
            fltdTasks = fltdTaskMapper.selectUnReadList(userCode);
        } else if ("2".equals(queryType)) {
            fltdTasks = fltdTaskMapper.selectReadList(userCode);
        } else if ("3".equals(queryType)) {
            fltdTasks = fltdTaskMapper.selectMessageList(param);
        }
        return fltdTasks;
    }

    @Override
    public List<FltdTask> selectUnReadList(String userCode) {
        return fltdTaskMapper.selectUnReadList(userCode);
    }

    @Override
    public List<FltdTask> selectReadList(String userCode) {
        return fltdTaskMapper.selectReadList(userCode);
    }

    @Override
    public Map<String, Object> checkGroup(FltdTaskVO taskVO) {
        //返回结果
        Map<String, Object> map = new HashMap<>();
        //本单位及下级部门
        List<String> deptList = new ArrayList<>();
        //符合条件的全部待办
        List<FltdTask> tasks = new ArrayList<>();
        //汇总校验结果
        boolean check = true;

        String nodeCode = "";
        //只查询当前节点的待办
        if ("Y".equals(taskVO.getExt2())) {
            nodeCode = taskVO.getNodeCode();
        }

        if (StringUtils.isNotEmpty(taskVO.getDeptCode())) {
            //按单位查询
            //查询当前待办所在的一级子公司及其下级部门
            List<XtzyCompany> companyList = xtzyCompanyService.getParantAndChildrens(taskVO.getDeptCode());
            if (CollectionUtils.isEmpty(companyList)) {
                //最顶级
                deptList.add(taskVO.getDeptCode());
            }
            for (XtzyCompany xtzyCompany : companyList) {
                deptList.add(xtzyCompany.getCompCode());
            }
            tasks = fltdTaskMapper.queryTasks(taskVO.getFlowNo(), taskVO.getAcctYear(), taskVO.getQuarterCode(), nodeCode, deptList,taskVO.getManageCompCode());
        } else {
            //查询所有单位的待办
            String flowNo = taskVO.getFlowNo();
            String acctYear = taskVO.getAcctYear();
            String quarterCode = taskVO.getQuarterCode();
            tasks = fltdTaskMapper.queryTasks(taskVO.getFlowNo(), taskVO.getAcctYear(), taskVO.getQuarterCode(), nodeCode, null,taskVO.getManageCompCode());
        }

        //汇总提交校验
        if (StringUtils.isNotEmpty(taskVO.getExt1())) {
            String max = "";
            for (FltdTask task : tasks) {
                if (task.getNodeCode().compareTo(max) > 0) {
                    max = task.getNodeCode();
                }
            }
            //漏发的数据直接提交
            if (taskVO.getNodeCode().compareTo(max) >= 0) {
                for (FltdTask task : tasks) {
                    if (task.getNodeCode().compareTo(max) > 0) {
                        max = task.getNodeCode();
                    }
                    //需要汇总的待办没有全部提交
                    if (!taskVO.getNodeCode().equals(task.getNodeCode())) {
                        check = false;
                        break;
                    }
                }
            }
        }

        map.put("check", check);
        map.put("tasks", tasks);
        return map;
    }

    @Override
    public List<FltdTask> selectUrgentTask() {
        return fltdTaskMapper.selectUrgentTask();
    }

    @Override
    public List<FltdTask> selectCurrentTasks(String procGuid, String nodeCode) {
        return fltdTaskMapper.selectCurrentTasks(procGuid, nodeCode);
    }

    @Override
    public Boolean selectCanSubmit(String procGuid, String nodeCode, String currUserCode) {
        if (StringUtils.isNotEmpty(procGuid) && StringUtils.isNotEmpty(nodeCode) && StringUtils.isNotEmpty(currUserCode)) {
            int result = fltdTaskMapper.selectCanSubmit(procGuid, nodeCode, currUserCode);
            return result == 0;
        } else {
            return false;
        }
    }

    @Override
    public List<FltdTask> selectAllTaskList() {
        return fltdTaskMapper.selectAllTaskList();
    }

    @Override
    public void closeTask(String todoGuid) {
        XtzyUser user = ShiroUtils.getUser();
        Date now = new Date();
        FltdTask fltdTask = fltdTaskMapper.selectByPrimaryKey(todoGuid);
        fltdTask.setStatus("close");
        fltdTask.setStatusName("完成");
        fltdTask.setFactEndDate(now);
        fltdTask.setAuditCode(user.getUserCode());
        fltdTask.setAuditName(user.getUserDesc());
        fltdTask.setUpdateBy(user.getUserCode());
        fltdTask.setUpdateTime(now);
        fltdTaskMapper.updateByPrimaryKeySelective(fltdTask);
    }

    @Override
    public List<FltdTask> selectBatchCurrentTasks(String procGuid, String nodeCode) {
        String[] split = procGuid.split(";");
        List<FltdTask> fltdTasks = fltdTaskMapper.selectBatchCurrentTasks(split, nodeCode);

        List resultList = fltdTasks.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(s -> s.getCurrUserCode()))), ArrayList::new));

        return resultList;
    }

    @Override
    public List<FltdTask> selectBatchExpertTasks(String ids) {
        //此处id就为bizGuid
        String[] bizGuids = ids.split(";");
        List<FltdTask> fltdTasks = new ArrayList<>();
        for (String bizGuid:bizGuids){
            String procId = fltdTaskMapper.selectProcId("fengxianjieticeping", null, bizGuid);
            List<FltdTask> fltds= fltdTaskMapper.selectCurrentTasks(procId, "B04");
            fltdTasks.addAll(fltds);
        }

        return fltdTasks;
    }

    @Override
    public List<String> selectProcIds(String flowNo, String taskGuid, String bizGuids) {
        String[] split = bizGuids.split(";");
        List<String> list = new ArrayList<>();
        for (String val:split){
            String s = fltdTaskMapper.selectProcId(flowNo, taskGuid, val);
            list.add(s);
        }
        return list;
    }

    @Override
    public List<FltdTask> selectCurrents(String procGuids, String nodeCode) {
        String[] split = procGuids.split(";");
        List<FltdTask> list = new ArrayList<>();
        for (String procGuid:split){
            List<FltdTask> fltdTasks = fltdTaskMapper.selectCurrentTasks(procGuid, nodeCode);
            list.addAll(fltdTasks);
        }

        return list;
    }

    @Override
    public List<FltdTask> selectTaskListData(FltdTaskVO param) {
        List<FltdTask> fltdTasks = new ArrayList<>();
        fltdTasks = fltdTaskMapper.selectTaskListData(param);
        return fltdTasks;
    }

    @Override
    public List<FltdTask> selectTaskListInFlowNo(FltdTaskVO param) {
        List<FltdTask> fltdTasks = new ArrayList<>();
        fltdTasks = fltdTaskMapper.selectTaskListInFlowNo(param);
        return fltdTasks;
    }

	@Override
	public void compensateClose() throws Exception {
		List<FltdTask> taskList = fltdTaskMapper.selectMothCloseTasks();
		for(FltdTask task : taskList){
			fltdOATaskService.deleteOA(task);
		}
	}

}
